// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const userCollection = db.collection('user')
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  const avatarState = event.avatarState || false
  const avatarSrc = event.avatarSrc || ''
  const bgState = event.bgState || false
  const bgSrc = event.bgSrc || ''

  const username = event.username || ''
  const sex = event.sex || ''
  const oneword = event.oneword || ''
  const tag = event.tag || []

  let infoList = {}

  let stateCode = 0

  let avatarFile = ''
  let bgpicFile = ''

  await userCollection.where({
    _openid: wxContext.OPENID
  }).get().then(res => {
    infoList = res.data[0]
    console.log(infoList)
  })
  if (avatarState && avatarSrc != ''){
    await cloud.uploadFile({
      cloudPath: 'userAvatar/' + infoList._id,
      fileContent: avatarSrc, // 文件路径
    }).then(res => {
      avatarFile = res.fileID
    }).catch(error => {
      console.log('头像上传失败！' + error)
    })
  }

  if (bgState && bgSrc != '') {
    await cloud.uploadFile({
      cloudPath: 'bgSrc/' + infoList._id,
      filePath: bgSrc, // 文件路径
    }).then(res => {
      bgpicFile = res.fileID
    }).catch(error => {
      console.log('背景上传失败！' + error)
    })
  }

  await userCollection.where({
    _openid: wxContext.OPENID
  }).update({
    data: {
      bgpic: bgpicFile == '' ? infoList.bgpic : bgpicFile,
      avatar: avatarFile == '' ? infoList.avatar : avatarFile,
      username: username == '' ? infoList.username : username,
      sex: sex == '' ? infoList.sex : sex,
      oneword: oneword == '' ? infoList.oneword : oneword,
      tag: tag.length == 0 ? infoList.tag : tag
    }
  }).then(res => {
    stateCode = 200
  })
  return stateCode
}